/*
 * @Author: 白川 杏 baiyufeisteam@163.com
 * @Date: 2023-05-30 08:06:10
 * @LastEditors: 白川 杏 baiyufeisteam@163.com
 * @LastEditTime: 2023-06-05 15:45:51
 * @FilePath: \herb-garden\backend\koaserver\routes\sign.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//订单 projectwork
const router = require('koa-router')()

router.prefix('/sign')

router.post('/getmysign', async (ctx, next) => {
    const userid = ctx.request.body.userid
    let sql = "select date from sign where userid=? order by id desc"
    let result = await ctx.db.EXCUTE(sql, [userid])
    console.log(result);
    ctx.body = {
        code: 200,
        data: result
    }
})
router.post('/addmysign', async (ctx, next) => {
    const userid = ctx.request.body.userid
    const date = ctx.request.body.date
    let sql = "insert into sign (userid, date, mask) values (?, ?, ?)"
    let result = await ctx.db.EXCUTE(sql, [userid, date, 1])
    // update dj_xwxx SET 浏览次数= CASE WHEN 浏览次数 IS NULL THEN 1 else 浏览次数 + 1 END where 新闻编号='*****'
    // let sql1 = 'update (select * from mycrops where userid=? and growth>60) set nowgrowday=case when nowgrowday=10 and nowgrownum=4 then 10 else nowgrownum<4 and nowgrowday+1'
    // let result1 = await ctx.db.EXCUTE(sql1, [userid])

    // console.log(result);
    // console.log(userid);
    // console.log(date);
    let result0 = await ctx.db.EXCUTE("select * from sign where userid=?", [userid])
    let result2 = await ctx.db.EXCUTE("select * from coin where userid=? order by date desc", [userid])
    console.log(result0.length);
    console.log(result2[0]);
    if(result0.length % 5 == 0){
        let sql1 = "insert into coin (userid, addcoin, date, sumcoin, type) values (?, 15, ?, ?, 1)"
        let result1 = await ctx.db.EXCUTE(sql1, [userid, date, result2[0].sumcoin+15])
    } else{
        let sql1 = "insert into coin (userid, addcoin, date, sumcoin, type) values (?, 5, ?, ?, 0)"
        let result1 = await ctx.db.EXCUTE(sql1, [userid, date, result2[0]?result2[0].sumcoin+15:5])
    }

    ctx.body = {
        code: 200,
        data: result
    }
})


//backend
//页面初始化时获取数据库内的数据条目
router.post('/getsignbackend', async (ctx, next) => {
    let result = await ctx.db.EXCUTE("SELECT n.*, (SELECT username FROM user ni WHERE n.userid=ni.userid) AS userinfo FROM sign n")
    
    ctx.body = {
        code: 200,
        data: result
    }
})

module.exports = router